﻿@*2020版 中途结算*@
@using Newtouch.Infrastructure;
@{
    ViewBag.Title = "PartialSettleIndex";
    Layout = "~/Views/Shared/_Form.cshtml";

    //是否和医保交易
    var openYbSett = SysConfigReader.Bool("Inpatient_Sett_OpenYbSett");
    //医保所属地，区分系统将执行何处医保逻辑
    var medicalInsurance = SysConfigReader.String("Inpatient_MedicalInsurance");

    //收费成功之后是否直接打印收据
    var autoPrintFP = SysConfigReader.Bool("Inpatient_Sett_AutoPrint");
    //收据报表链接
    var invoiceReportUrl = SysConfigReader.OrgReportLink("NewInpatientSett");

    var opr = Newtouch.Common.Operator.OperatorProvider.GetCurrent();
    var yesterday = DateTime.Now.AddDays(-1).ToString("yyyy-MM-dd 23:59:59");
}

@Html.Partial("_YibaoCommonView")
<div class="rows" style="margin-bottom: 1%;">
    <div class="panel panel-default" style="margin-bottom:0;">
        <div class="panel-heading navb-bg">
            住院患者信息
        </div>
        <table class="form" style="width:96%;">
            <tbody>
                <tr>
                    <th class="formTitle">住院号：</th>
                    <td class="formValue">
                        <input class="form-control" type="text" id="zyh" value="" />
                    </td>
                    <td class="formValue">
                        <input type="button" class="btn btn-default btn-md btn-default-color" title="选择住院患者" style="" id="zy_btnsyy" value="查询" onclick="GetPatSerarchView();">
                    </td>
                    <td class="formValue" style="width: 130px">
                        @if (openYbSett == true)
                        {
                            <div id="readCard" style="color: orangered;">
                                <input type="button"  id="btkhsr" value="证件号输入" class="form-control" style="border-color:#00a0e9; margin-left: 0px;margin-top: 2px; height: 22px;width:44px;padding-left:0px; float: left;vertical-align:central;" onclick="GetPatSbkh()" />
                                <i class="fa fa-id-card" style="font-size: 27px; float: left; vertical-align: central;" title="读卡"></i>
                                <select id="readCardCardType" class="form-control" style="width: 36px; height: 26px; padding: 0px; float: left; vertical-align: central;">
                                    @if (openYbSett == true)
                                    {
                                        <option value="03">社</option>
                                    }
                                    <option value="01">社(电)</option>
                                    <option value="02">身</option>
                                </select>
                            </div>
                        }
                    </td>
                    <th class="formTitle" style="width: 50px">开始时间：</th>
                    <td class="formValue" style="width:143px;">
                        <label id="startTime"></label>
                    </td>
                    <th class="formTitle">结束时间：</th>
                    <td class="formValue" style="width:143px;">
                        <input id="endTime" type="text" class="form-control input-wdatepicker form-an formClearIgnore"
                               onfocus="WdatePicker({ dateFmt: 'yyyy-MM-dd HH:mm:ss', onpicked: function () { thenreload(); } })" value="@(System.DateTime.Now.AddDays(-1).ToString("yyyy-MM-dd 23:59:59"))" />
                    </td>
                    <th class="formTitle">姓名：</th>
                    <td class="formValue">
                        <label id="zy_xm" style="min-width:100px"></label>
                    </td>
                    <th class="formTitle">性别：</th>
                    <td class="formValue">
                        <label id="zy_xb"></label>
                    </td>
                </tr>
            </tbody>
            <tbody class="dispTbody" style="display:none;">
                <tr>
                    <th class="formTitle"></th>
                    <td class="formValue" colspan="3">
                        <label></label>
                    </td>
                    
                    <th class="formTitle">年龄：</th>
                    <td class="formValue">
                        <label id="zy_nl"></label>
                    </td>
                    <th class="formTitle">入院诊断：</th>
                    <td class="formValue">
                        <label id="zy_ryzd"></label>
                    </td>
                    <th class="formTitle">出生日期：</th>
                    <td class="formValue" >
                        <label id="zy_csny" style="min-width:100px"></label>
                    </td>
                    <th class="formTitle">入院日期：</th>
                    <td class="formValue">
                        <label id="zy_ryrq" style="min-width:100px"></label>
                    </td>
                </tr>
            </tbody>
        </table>
        <div class="fa_icontoggle"><i class="fa fa-angle-double-down icontoggle" style="color:rgb(0, 160, 233);cursor:pointer;"></i></div>
    </div>
</div>
<ul id="myTab" class="nav nav-tabs">
    <li class="active"><a href="#wj" data-toggle="tab">未结费用</a></li>
    <li><a href="#yj" data-toggle="tab">历史已结</a></li>
</ul>
<div id="myTabContent" class="tab-content">
    <div class="tab-pane fade in active" id="wj">
        <div class="gridPanel">
            <table id="gridList"></table>
        </div>
    </div>
    <div class="tab-pane fade" id="yj">
        <div class="gridPanel">
            <table id="gridList2"></table>
        </div>
        <div style="margin:3px 0;">
            <span style="color:red;font-weight:bold;">*.撤销功能限制为撤销列表中最后一次结算</span>
        </div>
    </div>
</div>

<div class="rows" style="margin-bottom: 1%;margin-top: 1%;">
    <div class="panel panel-default" style="margin-bottom:0;padding:10px;">
        <table class="form" style="width:96%;">
            <tbody>
                <tr>
                    <th class="formTitle">未结费用：</th>
                    <td class="formValue" style="width:100px;">
                        <label id="lblSumje" style="color:red;font-weight: bold;font-size: large;"></label>
                    </td>
                    <th class="formTitle" style="width:105px;">上次结算结束时间：</th>
                    <td class="formValue">
                        <label id="lastValidMidwaySettTime"></label>
                    </td>
                </tr>
            </tbody>
        </table>
    </div>
</div>
@Html.Partial("_BottomButtonsView", new Newtouch.HIS.Web.Core.Models.BottomButtonViewModel()
{
    ShowKeyList = new int[] { 6,7, 8 },
    F8Text = "确认收费",
    F6Text = "撤销结算",
    F7Text = "转出院结算",
    F6Hidden = true,
    F7Hidden = true,
    F8Hidden = true,
})
<script type="text/javascript">


    var openYbSett = '@openYbSett' === 'True'; //开关配置：医保患者是否使用医保交易流程
    var isYbjyjz; //当前是否走医保交易的就诊
    var medicalInsurance = '@medicalInsurance';
    var curTime = $.getDate() + " 23:59:59";

    var ybkCardType = "@((int)EnumCardType.YBJYK)";//医保卡类型
    var xnkCardType = "@((int)EnumCardType.XNK)";//虚拟卡类型
    var ybCommonBackReturnData;//医保撤销最后一次结算结果
    var ybIsReadCard = false;
    var zyh;
    var cqPatInfo = {};

    //通过ls把住院号传过去
    var fromzyh = sessionStorage.getItem('zyh');
    var defaultShow = sessionStorage.getItem('defaultShow');
    if (fromzyh) {
        $('#zyh').val(fromzyh);
        zyh = fromzyh;
        sessionStorage.removeItem('zyh');
    }
    if (defaultShow) {
        sessionStorage.removeItem('defaultShow');
    }

    $(function () {
        initgridList1();
        initgridList2();
        $('#myTab li:eq(1) a').tab('show'); //会触发grid2加载样式

        if (!(defaultShow === 'yj')) {
            setTimeout("$('#myTab li:eq(0) a').tab('show');", 200); //显示未结
        }
    });

    function initgridList1() {
        if ($('#startTime').val() > $('#endTime').val()) {
            $.modalAlert("开始时间不能大于结束时间", "warning");
            return;
        }
        $('#gridList').dataGrid({
            unwritten: false,
            url: "/HospitalizationManage/BookkeepInHos/GetUnSettedFeeItemListJson",
            postData: { zyh: zyh, endTime: $("#endTime").val() },
            height: $(window).height() - 290,
            sortable: false,
            colModel: [
                { label: "收费项目名称", name: "sfxmmc", width: 180, align: "left" },
                {
                    label: "数量", name: "sl", width: 80, align: "left", formatter: "number"
                    , formatoptions: { decimalPlaces: 2, defaultValue: '0.00' }
                },
                {
                    label: "总金额", name: "zje", width: 80, align: "left", formatter: "number"
                        , formatoptions: { decimalPlaces: 2, defaultValue: '0.00' }
                },
            ],
            gridComplete: function (data) {
                var sumje = 0;
                if (data&&data.length > 0) {
                    $.each(data, function () {
                        sumje += this.zje;
                    });
                    if (sumje != 0) {
                        $('#lblSumje').html(sumje.toFixed(2));
                    }
                    else {
                        $('#lblSumje').html('');
                    }
                }
                jszje = sumje.toFixed(2);
            }
        });
    }

    var flagIsFirstInitGrid2 = true;
    $('a[data-toggle="tab"]').on('shown.bs.tab', function (e) {
        var targetHref = $(e.target).attr('href');
        $('#btn_bottombutton_f6,#btn_bottombutton_f7,#btn_bottombutton_f8').hide();
        if (targetHref && targetHref.indexOf('yj') != -1) {
            $('#btn_bottombutton_f6,#btn_bottombutton_f7').show();
            if (flagIsFirstInitGrid2) {
                flagIsFirstInitGrid2 = false;
            }
            reloadGrid2();
        }
        else {
            $('#btn_bottombutton_f8').show();
        }
    })

    function initgridList2() {
        $('#gridList2').dataGrid({
            unwritten: false,
            height: $(window).height() - 310,
            sortable: false,
            colModel: [
                { label: "jsnm", name: "jsnm", align: "left", hidden: true },
                { label: "住院号", name: "zyh", align: "left", hidden: true },
                {
                    label: "结算金额", name: "zje", width: 180, align: "left", formatter: "number"
                    , formatoptions: { decimalPlaces: 2, defaultValue: '0.00' }
                },
                {
                    label: "结算开始时间", name: "jsksrq", width: 240, align: "left",
                    formatter: "date", formatoptions: { srcformat: 'Y-m-d H:i:s', newformat: 'Y-m-d H:i:s' }
                },
                {
                    label: "结算结束时间", name: "jsjsrq", width: 240, align: "left",
                    formatter: "date", formatoptions: { srcformat: 'Y-m-d H:i:s', newformat: 'Y-m-d H:i:s' }
                },
                { label: "结算人员", name: "CreatorCode", width: 140, align: "left" },
                {
                    label: "结算时间", name: "CreateTime", width: 240, align: "left",
                    formatter: "date", formatoptions: { srcformat: 'Y-m-d H:i:s', newformat: 'Y-m-d H:i:s' }
                }
            ],
        });
    }

    function thenreload() {
        //加载未结
        reloadGrid();
        reloadLastValidMidwaySettTime();

        var targetHref = $('#myTab li.active a').attr('href');
        if (targetHref && targetHref.indexOf('yj') != -1) {
            reloadGrid2();  //当前已是已结
        }
    }

    function reloadGrid() {
        if ($("#startTime").val() > $("#endTime").val()) {
            $.modalAlert("开始时间不能大于结束时间", "warning");
            return;
        }
        $("#gridList").jqGrid('setGridParam', {
            postData: { zyh: zyh, endTime: $("#endTime").val() },
        }).trigger('reloadGrid');

    }

    function reloadGrid2() {
        $("#gridList2").jqGrid('setGridParam', {
            postData: { zyh: zyh },
            url:"/HospitalizationManage/BookkeepInHos/GetMidwaySettedListJson"
        }).trigger('reloadGrid');

    }

    function reloadLastValidMidwaySettTime() {
        //更新‘最后结算结束时间’
        $('#lastValidMidwaySettTime').html('');
        if (!!zyh) {
            $.najax({
                url: "/HospitalizationManage/BookkeepInHos/GetLastValidMidwaySettTimeJson?zyh=" + zyh,
                success: function (ajaxresp) {
                    if (ajaxresp.data) {
                        $('#lastValidMidwaySettTime').html($.getTime({ date: ajaxresp.data }));
                        $('#startTime').html($.getTime({ date: ajaxresp.data }));
                    }
                },
            });
        }
    }

    //病人查询
    function GetPatSerarchView() {
        $.modalOpen({
            id: "patSearch",
            title: "患者查询",
            url: "/PatientManage/AccountManage/PatSearchView?brzybzType=" + '@((int)EnumZYBZ.Bqz + "," + (int)EnumZYBZ.Djz)' + "&t=" + Math.random() + "&zyh=" + zyh,
            width: "700px",
            height: "600px",
            callBack: function (iframeId) {
                top.frames[iframeId].PatDbGrid(); //在弹出窗口事件
                //调用查询卡号和住院号
            }//窗口点确定的回调函数
        });

    }

    //手输社保卡号
    function GetPatSbkh() {
        $.modalOpen({
            id: "sbkhInput",
            title: "卡号输入",
            url: "/OutpatientManage/OutpatientReg/OutPatientSbkhInput?t=" + Math.random(),
            width: "300px",
            height: "150px",
            callBack: function (iframeId) {
                top.frames[iframeId].PatSbkhData();
            }
        });
    }
    //选择的病人 callback
    function getPatInfoAjax(selePatInfo) {
        $('#endTime').val('@(yesterday)'); //update endTime
        $('#zyh').val(selePatInfo.zyh);
        zyh = selePatInfo.zyh;
        ajaxLoadDataResult({ zyh: selePatInfo.zyh});
    }

    var patModel = null;
    var jszje = 0.00;
    //加载住院基本信息
    function ajaxLoadDataResult(obj, funcSuccCallback) {
        $('#startTime').html('');   //只有切换住院号的时候，才切换开始日期
            $.najax({
                type: "POST",
                data: obj,
                url: "/HospitalizationManage/DischargeSettle/GetPartialInpatientSettleStatusDetail",
                dataType: "json",
                success: function (ajaxresp) {
                    $('#lblSumje').text('0.00');
                    patModel = ajaxresp.data.InpatientSettPatInfo
                    cqPatInfo.zymzh = patModel.zyh;//住院号
                    setPatInfoModel();

                    thenreload();

                    isYbjyjz = openYbSett && patModel.brxz == '1' && patModel.CardType == "@((int)Newtouch.Infrastructure.EnumCardType.YBJYK)";

                },
                errorCallback: function (err) {
                    newtouch_event_f4();
                    $('#zyh').trigger('focus');
                }
            });
    }

    //初始化病人信息
    function setPatInfoModel() {
        zyh = patModel.zyh;
        $('#zyh').val(patModel.zyh);
        $('#zy_xm').html(patModel.xm);
        $('#zy_xb').html($.getGender(patModel.xb));
        $('#zy_nl').html(getAgeFromBirthTime({ begin: patModel.csny }).text);
        $('#zy_ryzd').html(patModel.ryzdmc);
        $('#zy_csny').html(patModel.csny ? patModel.csny.substring(0, 10) : '');
        $('#zy_ryrq').html(patModel.ryrq ? patModel.ryrq.substring(0, 10) : '');

        //$('#startTime').html(patModel.ryrq ? patModel.ryrq.substring(0, 10) : '');
        $('#startTime').html(patModel.ryrq ? patModel.ryrq.replace('T',' '): '');
    }


    function hisSubmit(isYbjyjz, ybjyFeeReturn) {
        var zyh = patModel.zyh;
        var ryrq = $.getDate({ date: patModel.ryrq });
        var zje = ovpraseFloat(jszje).toFixed(2);
        //
        var widthpx = "600px";
        var heightpx = "400px";
        var hzjslx = "0";//0自费  1医保  8农保
        if (isYbjyjz && ybjyFeeReturn) {
            sessionStorage.setItem('ybjyFeeReturn', JSON.stringify(ybjyFeeReturn));
            sessionStorage.setItem('cqPatInfo', JSON.stringify(cqPatInfo));
            widthpx = "700px";
            heightpx = "500px";
            hzjslx = "1";
            ybjyFeeReturn.cqtczf = ybjyFeeReturn.hifp_pay;
            ybjyFeeReturn.zhzf = ybjyFeeReturn.acct_pay;
            ybjyFeeReturn.cqxjzf = ybjyFeeReturn.psn_cash_pay;
            ybjyFeeReturn.gwybz = ybjyFeeReturn.cvlserv_pay;
            ybjyFeeReturn.delpje = ybjyFeeReturn.hifob_pay;
            ybjyFeeReturn.dbzddyljgdz = ybjyFeeReturn.hosp_part_amt;
            ybjyFeeReturn.zhye = ybjyFeeReturn.balc;
            ybjyFeeReturn.jylsh = ybjyFeeReturn.setl_id;
            ybjyFeeReturn.zxjssj = ybjyFeeReturn.setl_time;
        }

        var openUrl = "/HospitalizationManage/DischargeSettle/ConfirmForm?zyh=" + zyh;
        openUrl += "&ryrq=" + (!!ryrq ? ryrq : '');
        openUrl += "&zje=" + (!!zje ? ovpraseFloat(zje).toFixed(2) : '');
        openUrl += "&xjzfys=" + (!!zje ? ovpraseFloat(zje).toFixed(2) : '');
        openUrl += "&patid=" + patModel.patId;
        openUrl += "&isXnhjy=";
        openUrl += "&isYbjy=" + (!!isYbjyjz) + "&brxz=" + patModel.brxz + "&brxzmc=" + patModel.brxzmc+ "&ztjs=" + true,
            $.modalOpen({
                id: "ConfirmFeeForm",
                title: "中途结算",
                url: openUrl,
                width: widthpx,
                height: heightpx,
                callBack: function (iframeId) {
                    top.frames[iframeId].AcceptClick(function (feeRelated, outTradeNo) {
                        var startTime = $('#startTime').html();
                        if (!!!startTime) {
                            $.modalAlert("未指定结算开始时间", 'error');
                            return;
                        }
                        if (!!!zyh) {
                            $.modalAlert("请选择住院病人", 'error');
                            return;
                        }
                        var thisSettEndTime = $('#endTime').val();
                        if (!!!thisSettEndTime) {
                            $.modalAlert("未指定结算结束时间", 'error');
                            return;
                        }

                        if ($("#startTime").val() > $("#endTime").val()) {
                            $.modalAlert("开始时间不能大于结束时间", "warning");
                            return;
                        }

                        var allLine = $("#gridList").jqGrid('getRowData_AllLine', null, true);
                        if (!!!allLine || allLine.length == 0) {
                            $.modalAlert("无未结费用", 'error');
                            return;
                        }
                       
                        //提交
                        var postData = { zyh: zyh, startTime: startTime, endTime: thisSettEndTime, fph: feeRelated.fph, feeRelated: feeRelated, ybfeeRelated: ybjyFeeReturn, jslx: hzjslx, outTradeNo: outTradeNo };
                        $.submitForm({
                            type: "POST",
                            url: "/HospitalizationManage/DischargeSettle/PartialSettleSave",
                            param: postData,
                            success: function (ajaxresp) {
                                var message = "";
                                sessionStorage.setItem('zyh', zyh);

                                $.modalMsg("结算成功" + message, 'success');
                                $.modalClose("ConfirmFeeForm");
                                newtouch_event_f4();
                                //打印发票
                                if (ajaxresp.data && ajaxresp.data.jsnm) {
                                    if ('@(autoPrintFP)' == 'True') {
                                        //报表打印
                                        var uri = '@Html.Raw(invoiceReportUrl)' + "&jsnm=" + ajaxresp.data.jsnm;
                                        window.open(uri, "_blank", "height=500, width=1195,top=100, left=50, toolbar =no, menubar=no, scrollbars=yes, resizable=yes, location=no, status=no");

                                    }
                                }
                            }
                        });
                    });
                },
                cancelCallBack: function (iframeId) {
                    //取消出院结算，出院办理回退
                    if (isYbjyjz) {
                        //if (medicalInsurance == "chongqing") {
                            var cqybjyDenySettleReturn;
                            var payoptype = { hisId:zyh,'setl_id': ybjyFeeReturn.setl_id, 'operatorId': '@(opr.rygh)', 'operatorName': '@(opr.UserName)', 'mdtrt_id': ybjyFeeReturn.mdtrt_id, 'psn_no': cqPatInfo.grbh, "insuplc_admdvs": cqPatInfo.xzqh };
                            $.ajax({
                                type: "POST",
                                url: "http://127.0.0.1:33333/api/YiBao/HospitaUpSettlement_2305",
                                dataType: "json",
                                data: payoptype,
                                async: false,
                                success: function (data) {
                                    cqybjyDenySettleReturn = eval('(' + data + ')');
                                }
                            });
                            if (cqybjyDenySettleReturn.infcode !== "0") {
                                $.modalAlert('住院结算冲正失败：' + cqybjyDenySettleReturn.ErrorMsg + '【此时医保已经结算成功，请联系his开发商处理】', 'error');
                            }

                            $.loading(false);
                        //}
                    }
                }
            });
    }

    function newtouch_event_f4() {
        $('#zyh').val('');
        sessionStorage.removeItem('zyh');
        $('#startTime').html('');

        $('#endTime').val('@(yesterday)');
        $('#zy_xm').html('');
        $('#zy_xb').html('');
        $('#zy_nl').html('');
        $('#zy_ryzd').html('');
        $('#zy_csny').html('');
        $('#zy_ryrq').html('');
        patModel = null;
        jszje = 0.00;
        flagIsFirstInitGrid2 = true;
        $('#myTab li:eq(1) a').tab('show'); //会触发grid2加载样式
        $('#lblSumje').text('0.00');
        $('#gridList').jqGrid("clearGridData");
        $('#gridList2').jqGrid("clearGridData");
        zyh = "";
    }


    //撤销结算
    function newtouch_event_f6() {
        if (!zyh) {
            $.modalAlert("住院号为空，请确认", 'warning');
            return;
        }
        $.ajax({
            type: "GET",
            url: "/HospitalizationManage/DischargeSettle/GetCQLastjsnm?zyh=" + zyh,
            dataType: "json",
            async: false,
            success: function (jsnm) {
                if (isYbjyjz) {
                    if (!ybIsReadCard) {
                        $.modalAlert("医保患者取消结算，请先读卡！", 'warning');
                        return;
                    }
                        var cqybjyDenySettleReturn;
                        $.ajax({
                            type: "GET",
                            url: "/HospitalizationManage/DischargeSettle/GetCancelSettInfo?jsnm=" + jsnm,
                            dataType: "json",
                            async: false,
                            success: function (canceldata) {
                                if (canceldata) {
                                    $.ajax({
                                        type: "POST",
                                        url: "http://127.0.0.1:33333/api/YiBao/HospitaUpSettlement_2305",
                                        dataType: "json",
                                        data: canceldata,
                                        async: false,
                                        success: function (data) {
                                            cqybjyDenySettleReturn = eval('(' + data + ')');
                                        }
                                    });
                                    if (cqybjyDenySettleReturn.infcode == "0") {
                                        Docancelhissubmit(jsnm, cqybjyDenySettleReturn.output.setlinfo);
                                    } else {
                                        $.modalAlert('住院结算冲正失败：' + cqybjyDenySettleReturn.err_msg + '【此时医保已经结算成功，请联系his开发商处理】', 'warning');
                                        return;
                                    }
                                } else {
                                    $.modalAlert('取消结算失败，结算表cqyb_OutPut05中无该次结算医保落地数据：结算内码' + jsnm, 'warning');
                                    return;
                                }
                                $.loading(false);
                            }
                        });
                } else {
                    Docancelhissubmit(jsnm);
                }
            }
        });
    }

    //转出院结算
    function newtouch_event_f7() {
        $.najax({
            url: "/HospitalizationManage/DischargeSettle/TransfertoCYsettle?zyh=" + zyh,
            success: function (ajaxresp) {
                var ybresp = { zyh: zyh, jslsh: ajaxresp.data };
                $.ajax({
                    type: "POST",
                    url: "http://127.0.0.1:33333/api/CQYiBao/UpdateSettType",
                    dataType: "json",
                    data: ybresp,
                    async: false,
                    success: function (data) {
                        var medicalReg = eval('(' + data + ')');
                        if (medicalReg) {
                            if (medicalReg.Code === "1") {
                                $.loading(false);
                                $.modalMsg("结算成功", 'success');
                                newtouch_event_f4();
                            }
                            else {
                                $.loading(false);
                                $.modalAlert("医保住院修改就诊登记失败：" + medicalReg.ErrorMsg, 'error');
                                return;
                            }
                        }
                    }
                });
            },
        });
    }

    //结算
    function newtouch_event_f8() {
        if (!!!zyh || !!!$('#zyh').val()) {
            $.modalAlert("请选择住院病人", 'error');
            return;
        }

        var startTime = $('#startTime').html();
        if (!!!startTime) {
            $.modalAlert("未指定结算开始时间", 'error');
            return;
        }
        if (!!!zyh) {
            $.modalAlert("请选择住院病人", 'error');
            return;
        }
        var thisSettEndTime = $('#endTime').val();
        if (!!!thisSettEndTime) {
            $.modalAlert("未指定结算结束时间", 'error');
            return;
        }

        if (startTime > thisSettEndTime) {
            $.modalAlert("开始时间不能大于结束时间", "warning");
            return;
        }
        var allLine = $("#gridList").jqGrid('getRowData_AllLine', null, true);
        if (!!!allLine || allLine.length == 0) {
            $.modalAlert("无未结费用", 'error');
            return;
        }


        if (isYbjyjz) {//医保
            if (!medicalInsurance) {
                $.modalAlert("程序未动态配置医保地，请配置后重试", 'warning');
                return;
            }
                if (!ybIsReadCard) {
                    $.modalAlert("医保患者结算，请先读卡！", 'warning');
                    return;
                }
                $.loading(true, '正在进行就诊登记修改，请稍后...');
                setTimeout(function() {
                    CQjzdj(function (jzxx) {
                            $.loading(true, '正在进行明细上传，请稍后...');
                            setTimeout(function() {
                                CQmxsc(jzxx,
                                        function (mxxx) {
                                            $.loading(true, '正在进行医保结算，请稍后...');
                                            setTimeout(function() {
                                                CQybjs(jzxx, mxxx);
                                                });
                                        });
                                },
                                50);
                        });
                    },
                    50);
        }
        else
        {
            hisSubmit();
        }
    }

    //本地操作取消结算
    function Docancelhissubmit(jsnm,ybBackReturnData)
    {
        var allLine = $("#gridList2").jqGrid('getRowData_AllLine', null, true);
        if (!!!allLine || allLine.length == 0) {
            $.modalAlert("无历史已结", 'error');
            return;
        }
        ybCommonBackReturnData = ybBackReturnData;
        $.modalOpen({
            id: "refundForm",
            title: "退费详情",
            url: "/HospitalizationManage/DischargeSettle/CancelPartialConfirmForm?jsnm=" + jsnm + "&patid=" + patModel.patId,
            width: "300px",
            height: "350px",
            callBack: function (iframeId) {
                top.frames[iframeId].submitform(); //在弹出窗口事件
            }
        });
    }

    function CancelTheLastMidwaySett(zffs1, zffsmc1,jsnm) {
        var postData = { zyh: zyh, zffs1: zffs1, zffsmc1: zffsmc1 };
        $.submitForm({
            type: "POST",
            url: "/HospitalizationManage/BookkeepInHos/CancelTheLastMidwaySett",
            param: postData,
            success: function (ajaxresp) {
                sessionStorage.setItem('zyh', zyh);
                sessionStorage.setItem('defaultShow', 'yj');
                if (isYbjyjz) {
                        ybCommonBackReturnData.jsnm = jsnm;
                        $.najax({
                            type: "POST",
                            data: {
                                entity: ybCommonBackReturnData, jslb: "4"
                            },
                            url: "/OutpatientManage/OutpatCharge/SaveChongQing99HQ",
                            dataType: "json",
                            loading: false,
                            success: function () {
                                newtouch_event_f4();
                            }
                        });
                } else {
                    newtouch_event_f4();
                }
            },
        });
    }

</script>
<script type="text/javascript">

    //重庆医保
    function CQjzdj(funcSuccCallback) {
	     $.ajax({
		    type: "POST",
		    url: "/PatientManage/HospiterRes/GetCQjzdjInfo",
		    data: { zyh: patModel.zyh },
		    dataType: "json",
		    cache: false,
		    async: false,
		    success: function (payoptype) {
		    	if (!payoptype) {
				    $.loading(false);
				    $.modalAlert("获取住院就诊登记失败", 'error');
				    return;
		    	}
		    	payoptype.mdtrt_cert_type = cqPatInfo.ybklx;
		    	payoptype.orgId = "@opr.OrganizeId";
		        $.ajax({
		            type: "POST",
		            url: "http://127.0.0.1:33333/api/YiBao/HospitaMdtrtinfo_2403",
		            dataType: "json",
		            data: payoptype,
		            async: false,
		            success: function (data) {
		                var medicalReg = eval('(' + data + ')');
		                if (medicalReg) {
		                    if (medicalReg.infcode == "0") {
		                        var jzxx = { mdtrt_id: payoptype.mdtrt_id, med_type: payoptype.med_type, djxx: payoptype };
		                        funcSuccCallback(jzxx);
		                    }
		                    else {
		                        $.loading(false);
		                        $.modalAlert("住院信息变更失败：" + medicalReg.err_msg, 'error');
		                        return;
		                    }
		                }
		            }
		        });
		    }
	    });
    }
    //审批判定，调用22接口查看是否有未审批数据
    function CQsppd(mxxx, funcSuccCallback) {
        var parameter1 = { "zyh": patModel.zyh, "splx": "1", "rq": $.getDate({ date: patModel.ryrq }), "xzlb": "1" };
        var parameter2 = { "zyh": patModel.zyh, "splx": "2", "rq": $.getDate({ date: patModel.ryrq }), "xzlb": "1" };
        var spGsfReturn;
        var spBdbReturn;
        $.ajax({
            type: "POST",
            url: "http://127.0.0.1:22222/api/CQYiBao/GetApprovalXm",
            data: parameter1,
            dataType: "json",
            async: false,
            success: function (data) {
                spGsfReturn = eval('(' + data + ')');
            }
        });
        $.ajax({
            type: "POST",
            url: "http://127.0.0.1:22222/api/CQYiBao/GetApprovalXm",
            data: parameter2,
            dataType: "json",
            async: false,
            success: function (data) {
                spBdbReturn = eval('(' + data + ')');
            }
        });
        if (!!spGsfReturn && !!spBdbReturn && spGsfReturn.Code === "1" && spBdbReturn.Code === "1") {
            if (!!spGsfReturn.Data && spGsfReturn.Data.cfmxlshList.length > 0) {
                $.loading(false);
                $.modalAlert("患者有高收费项目还未审批，请联系医保办审批后再次结算！", 'error');
                return;
            }
            if (!!spBdbReturn.Data && spBdbReturn.Data.cfmxlshList.length > 0) {
                $.loading(false);
                $.modalAlert("患者有白蛋白项目还未审批，请联系医保办审批后再次结算！", 'error');
                return;
            }
        } else {
            $.loading(false);
            $.modalAlert("调用医保22接口失败", 'error');
            return;
        }
        if (funcSuccCallback) {
            funcSuccCallback(mxxx);
        }
    }
    function CQmxsc(jzxx,funcSuccCallback) {
        var n = 1;
        var ybzje = 0.00;
        var succTimes = 0;
        var mxnum = 0;
        var isuccer = true;//明细上传是否成功
        //var zfzje = 0.00;

        //每次重新上传，先把以前上传的，但未结算的处方退掉
        var mxscobj = { hisId: patModel.zyh, mdtrt_id: jzxx.mdtrt_id, feedetl_sn: "0000", psn_no: cqPatInfo.grbh, operatorId: '@(opr.rygh)', operatorName: '@(opr.UserName)', insuplc_admdvs: cqPatInfo.xzqh };
	    $.ajax({
            type: "POST",
            url: "http://127.0.0.1:33333/api/YiBao/HospitaUpDscginfo_2302",
            data: mxscobj,
            dataType: "json",
            async: false,
            success: function (data) {
            }
        });
	    $.najax({
	        type: "GET",
	        data: {
	            mzzyh: patModel.zyh,cflx:'2'
	        },
	        url: "/HospitalizationManage/DischargeSettle/GetNogjybdm",
	        dataType: "json",
	        async: false,
	        loading: false,
	        success: function (ajaxResp) {
	            var xmmc = ajaxResp.xmmc;
	            if (xmmc) {
	                $.loading(false);
	                isuccer = false;
	                $.modalAlert(xmmc + "未对照国家医保编码!请核实", 'error');
	                return;
	            }
	            else {
	                var ybresp = { hisId: patModel.zyh, psn_no: cqPatInfo.grbh, med_type: jzxx.med_type, insuplc_admdvs: cqPatInfo.xzqh, operatorId: "@opr.rygh", operatorName: "@opr.UserName", orgId: "@opr.OrganizeId", uploadCount: "50" };
	                $.ajax({
	                    type: "POST",
	                    url: "http://127.0.0.1:33333/api/YiBao/HospitaFeedetail_2301",
	                    data: ybresp,
	                    dataType: "json",
	                    async: false,
	                    success: function (data) {
	                        var upDataReturn = eval('(' + data + ')');
	                        if (upDataReturn.infcode == "0") {

	                            $.najax({
	                                type: "GET",
	                                data: {
	                                    mzzyh: patModel.zyh
	                                },
	                                url: "/HospitalizationManage/DischargeSettle/GetCQAlreadyUploadFeeDetails",
	                                dataType: "json",
	                                async: false,
	                                loading: false,
	                                success: function (ajaxResp) {
	                                    ybzje = ajaxResp.ybzje;
	                                }
	                            });
	                        }
	                        else {
	                            $.loading(false);
	                            isuccer = false;
	                            $.modalAlert("明细上传失败：" + upDataReturn.err_msg, 'error');
	                            return;
	                        }

	                    }
	                });
	            }
	        }
	    });
        $.loading(false);
        if (funcSuccCallback && isuccer) {
            setTimeout(function () {
                var mxxx = { ybzje: ybzje };
                funcSuccCallback(mxxx);
            }, 50);
        }
    }
    function CQybjs(jzxx,mxxx) {
	    $.ajax({
		    type: "GET",
		    url: "/HospitalizationManage/DischargeSettle/GetCQJsPatInfo?zyh=" + patModel.zyh,
		    dataType: "json",
		    async: false,
		    success: function (ajaxresp) {
		        if (ajaxresp) {
		            var jzlx = cqPatInfo.ybklx
			        var predata = {
			            psn_no: cqPatInfo.grbh,
			            mdtrt_cert_type: cqPatInfo.ybklx,
			            mdtrt_cert_no: jzlx == "01" ? cqPatInfo.ecToken : (jzlx == "02" ? cqPatInfo.sfzh : cqPatInfo.sbkh),
			            medfee_sumamt: mxxx.ybzje,
			            psn_setlway: "01",
			            mdtrt_id: jzxx.mdtrt_id,
			            insutype: cqPatInfo.xzlx,
			            mid_setl_flag: "1",
			            insuplc_admdvs: cqPatInfo.xzqh,
			            operatorId: '@(opr.rygh)',
			            operatorName: '@(opr.UserName)',
			            hisId: patModel.zyh,
			            acct_used_flag: "1",
			            dscgTime: ajaxresp.cyrq
			        };
			        var ybjsSettReturn1;
			        var ybjsSettReturn;
			        $.ajax({
			            type: "POST",
			            url: "http://127.0.0.1:33333/api/YiBao/HospitaSettlement_2303",
			            data: predata,
			            dataType: "json",
			            async: false,
			            success: function (data) {
			                ybjsSettReturn1 = eval('(' + data + ')');
			            }
			        });
				    if (ybjsSettReturn1) {
				        if (ybjsSettReturn1.infcode == "0") {
						    $.ajax({
							    type: "POST",
							    url: "http://127.0.0.1:33333/api/YiBao/HospitaSettlement_2304",
							    data: predata,
							    dataType: "json",
							    async: false,
							    success: function (data) {
								    ybjsSettReturn = eval('(' + data + ')');
							    }
						    });
						    if (ybjsSettReturn) {
							    $.loading(false);
							    if (ybjsSettReturn.infcode == "0") {
							        var ybjyCqFeeReturn = ybjsSettReturn.output.setlinfo;
								    //his结算确认（包括医保结算确认）
								    //根据后台查询出的结果，如果该患者有开立自立的项目（没有医保代码），则结算时的总金额，填写总的汇总金额
								    //如果只有医保项目，则以医保结算的医保返回结果为准进行结算
								    ybjyCqFeeReturn.his_hisfyze = jszje;
								    ybjyCqFeeReturn.ybzje = mxxx.ybzje;
								    ybjyCqFeeReturn.jzid = jzxx.mdtrt_id;
								    hisSubmit(true, ybjyCqFeeReturn, false, null);
							    } else {
								    $.loading(false);
								    $.modalAlert(ybjsSettReturn.ErrorMsg, 'error');
								    return;
							    }
						    } else {
							    $.loading(false);
							    $.modalAlert("调用医保接口失败", 'error');
							    return;
						    }
					    } else {
						    $.loading(false);
						    $.modalAlert(ybjsSettReturn1.ErrorMsg, 'error');
						    return;
					    }
				    } else {
					    $.loading(false);
					    $.modalAlert("调用医保接口失败", 'error');
					    return;
				    }

			    } else {
				    $.modalAlert('获取结算患者信息失败，请重试', 'warning');
				    return;
			    }
			    $.loading(false);
		    }
	    });

    }
    function upLoadReturnData(retdata) {
        $.najax({
            url: '/HospitalizationManage/DischargeSettle/upLoadReturnData',
            data: { upReturnData: retdata, patzyh: zyh },
            type: 'POST',
            success: function () {

            }
        });
    }
    //查询条件
    function getSearchPostData(n) {
        var zyh = patModel.zyh;
        var pagination = {
            rows: 50,
            page: n + 1,
            sidx: 'yka105 asc'
        };
        return { pagination: pagination, zyh: zyh };

    }
    //查询条件
    function getSearchCQPostData(n) {
	    var zyh = patModel.zyh;
	    var pagination = {
	        rows: 10,
	        page: 1,
		    //page: n + 1,
		    sidx: ' cxmxlsh asc'
	    };
	    return { pagination: pagination, zyh: zyh };

    }
    function ovpraseFloat(val) {
        if (!val) {
            val = 0.00;
        }
        return parseFloat(val);
    }
    //获取结算患者 患者信息
    function funcGetSettPatientInfo(funcSuccCallback) {
        $.najax({
            url: '/HospitalizationManage/DischargeSettle/GetInpatientSettYbPatInfo?zyh=' + patModel.zyh,
            loadingtext: "正在请求患者出院信息，请稍后...",
            type: 'POST',
            success: function (ajaxResp) {
                //
                if (funcSuccCallback) {
                    setTimeout(function () {
                        funcSuccCallback(ajaxResp.data);
                    }, 50);
                }
            }
        });
    }
</script>
<script type="text/javascript">
    //
    function readCard() {
              GetReadCardInfo(null);
    }
    //读卡
    function GetReadCardInfo(sbkobj) {
        var cardInfo1;
        var cardInfo2;
        var cardInfo3;
        var yibaoCardInfo;
        var patsbkh = null;

        var url = "http://127.0.0.1:33333/api/YiBao/CardecInfo_1161";
        var payoptype = { "mdtrt_cert_type": $('#readCardCardType').val(), "operatorId": '@(opr.rygh)', "operatorName": '@(opr.UserName)', "businessType": "01101", "officeId": "0201", "officeName": "内科" };
        if ($('#readCardCardType').val() === "02") {
            payoptype.mdtrt_cert_no = sbkobj.sbkh;
            url = "http://127.0.0.1:33333/api/YiBao/CardecInfo_1101";
        }
        else if ($('#readCardCardType').val() === "01") {
            url = "http://127.0.0.1:33333/api/YiBao/CardecInfo_1162";
        }
        $.ajax({
            type: "POST",
            url: url,
            dataType: "json",
            data: payoptype,
            async: false,
            success: function (data) {
                yibaoCardInfo = eval('(' + data + ')');
            }
        });
        $.loading(false);
        if (yibaoCardInfo) {
            if (yibaoCardInfo.infcode == "0") {
                if (!yibaoCardInfo || !yibaoCardInfo.output.baseinfo || !yibaoCardInfo.output.insuinfo[0]) {
                    $.modalAlert("读卡失败:" + yibaoCardInfo.err_msg, 'error');
                    return;
                }
                var ybklx = $('#readCardCardType').val();
                cardInfo1 = yibaoCardInfo.output.baseinfo; //医保基本信息
                cardInfo2 = yibaoCardInfo.output.insuinfo[0];//参保信息
                if (ybklx !== "02") {
                    cardInfo3 = yibaoCardInfo.output.cardecinfo;//卡信息
                    cqPatInfo.ecToken = cardInfo3.ecToken;
                    cqPatInfo.sbkh = cardInfo3.cardno;
                }

                cqPatInfo.xm = cardInfo1.psn_name;
                cqPatInfo.sfzh = cardInfo1.certno;
                cqPatInfo.xzqh = cardInfo2.insuplc_admdvs;
                cqPatInfo.cblb = cardInfo2.psn_type;
                cqPatInfo.xzlx = cardInfo2.insutype;
                cqPatInfo.grbh = cardInfo1.psn_no;
                cqPatInfo.ybklx = ybklx;
                cqPatInfo.jslx = "2";
                yibaoCardInfo.readCardCardType = ybkCardType;
                yibaoCardInfo.kh = ybklx == "03" ? cardInfo3.cardno : null;
                yibaoCardInfo.qtjz = ybklx != "03" ? cardInfo1.certno : null;
                //yibaoCardInfo.kh = ybklx =="01"?cardInfo1.certno:(ybklx=="02" ? cardInfo1.certno:cardInfo3.cardno) ;
                //社保编号 暂作为系统卡号
                ybIsReadCard = true;
                ajaxLoadDataResult({ kh: yibaoCardInfo.kh, sfz: yibaoCardInfo.qtjz, cardType: ybkCardType });
            } else {
                $.modalAlert("刷卡失败:" + yibaoCardInfo.err_msg, 'error');
            }
        } else {
            $.modalAlert("刷卡获取医保信息失败！失败原因：医保中心无信息返回，请重试！", 'error');
        }

    }

    $('#readCard i').click(function () {
        if (false) {
            $.modalAlert("等等情况不可以触发读卡", 'warning');
            return;
        }
        setTimeoutReadCard();
    })
    //触发读卡
    function setTimeoutReadCard() {
        $.loading(true, '正在读卡，请稍后…');
        setTimeout("readCard();", 50);
    }
</script>
